<template>
	<div class="docmanagement">
		<div class="crumbs-wrapper">
			<Crumbs title="文档管理" />
		</div>
		<div class="main">
			<el-form :inline="true">
				<el-form-item label="文档名称">
					<el-input v-model="searchFormData.docName" placeholder="请输入"></el-input>
				</el-form-item>
				<el-form-item label="上传人">
					<el-input v-model="searchFormData.createdBy" placeholder="请输入"></el-input>
				</el-form-item>
				<el-form-item label="上传时间">
					<el-date-picker
					      v-model="dateRange"
					      type="daterange"
					      range-separator="至"
					      start-placeholder="开始日期"
					      end-placeholder="结束日期">
					    </el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button @click="reset">重置</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="search">查询</el-button>
				</el-form-item>
				<el-form-item v-if="permissions.create">
					<el-button type="primary" @click="showDocDialog('new')">新增</el-button>
				</el-form-item>
				<el-form-item v-if="permissions.delete">
					<el-button type="primary" :disabled="docSelection.length==0" @click="deleteDoc">批量删除</el-button>
				</el-form-item>
			</el-form>
			<el-row>
				<el-table :data="tableData" size="mini"
					:header-cell-style="{ background: '#FAFAFA', textAlign: 'center' }"
					:cell-style="{ textAlign: 'center' }" v-loading="tableLoading" 
					@select="rowSelect">
					<el-table-column type="selection" width="55"> </el-table-column>
					<el-table-column prop="docName" label="文档名称"> </el-table-column>
					<el-table-column label="文档大小">
						<template slot-scope="scope">
							{{scope.row.fileSize/1000}}KB
						</template>
					</el-table-column>
					<el-table-column prop="createdBy" label="上传人"> </el-table-column>
					<el-table-column prop="createdTime" label="上传时间">
					</el-table-column>
					<el-table-column label="操作">
						<template slot-scope="scope">
							<template v-if="permissions.update">
								<el-button type="text" @click="showDocDialog('edit', scope.row)">编辑</el-button>
							</template>
							<template v-if="permissions.delete">
								<el-button type="text" @click="deleteDoc(scope.row)">删除</el-button>
							</template>
							<template v-if="permissions.download">
								<el-button type="text" @click="downloadDoc(scope.row)">下载</el-button>
							</template>
						</template>
					</el-table-column>
				</el-table>
			</el-row>
			<br>
			<el-row>
				<!-- 分页 -->
				<el-pagination background align="center" @size-change="pageSizeChange"
					@current-change="currentPageChange" :current-page="searchFormData.pageNum"
					:page-sizes="[5, 10, 15, 20]" :page-size="searchFormData.pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="searchFormData.total">
				</el-pagination>
			</el-row>
		</div>
		<!-- 新增编辑对话框 -->
		<el-dialog :title="docDialogType == 'edit' ? '文档编辑' : '文档新增'" :visible.sync="dialogVisible" width="30%">
			<el-form label-width="100px">
				<el-form-item label="文档名称" prop="name">
					<el-input size="small" v-model="docFormData.docName"></el-input>
				</el-form-item>
				<el-form-item label="上传文件">
					<el-upload action="/api/file/info/addWork" ref="refDocUploder" 
						:limit="1" :file-list="docFiles" name="file"
						:before-upload="beforeUpload"
						:on-error="(e) => { this.$message.error('文件上传失败,请检查文件格式后重试') }"
						:on-success="uploadsuccess">
						<el-button size="small" type="success" @click="">上传文件</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" @click="dialogVisible = false">取 消</el-button>
				<el-button v-if="docDialogType == 'new'" size="small" type="primary" @click="saveDoc">保存</el-button>
				<el-button v-if="docDialogType == 'edit'" size="small" type="primary" @click="editDoc">保存</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				docDialogType: 'new',
				docFiles: [],
				dialogVisible: false,
				dateRange: ['',''], //查询日期范围
				searchFormData: {
					docName: '',
					createdBy: '',
					beginDate: '',
					finishDate: '',
					pageNum: 1,
					pageSize: 10,
					total: 0
				},
				tableData: [],
				tableLoading: false,
				docFormData: {
					docName: '',
					filePath: '',
					fileSize: '',
					businessType: '3' //所属模块，0-认证资料，1-资源管理，2-用户信息,3-文档管理
				},
				docSelection: [], //已勾选的文档集合
				rules: {
					name: [{
							required: true,
							message: '请输入活动名称',
							trigger: 'blur'
						},
						{
							min: 3,
							max: 5,
							message: '长度在 3 到 5 个字符',
							trigger: 'blur'
						}
					],
				}
			}
		},
		computed: {
			permissions() {
				return {
					create: !!this.btns?.find(btn=>btn.perms=='file:info:add'),
					update: !!this.btns?.find(btn=>btn.perms=='file:info:edit'),
					delete: !!this.btns?.find(btn=>btn.perms=='file:info:remove'),
					download: !!this.btns?.find(btn=>btn.perms=='file:info:download')
				}
			}
		},
		watch: {
			dateRange(newVal) {
				if(newVal) {
					this.searchFormData.beginDate = this.$util.date2string(this.dateRange[0]).dateStr
					this.searchFormData.finishDate = this.$util.date2string(this.dateRange[1]).dateStr 
				}
			}
		},
		created() {
			this.btns = JSON.parse(sessionStorage.getItem('menus') || '[]').find(menu=>menu.path=='/docManagement')?.children;
		},
		mounted() {
			this.tableLoading = true;
			this.loadTableData()
		},
		methods: {
			rowSelect(list) {
				this.docSelection = list;
			},
			showDocDialog(type, row) { //打开文档添加/编辑窗口
				this.docDialogType = type;
				this.dialogVisible = true;
				if(row) {
					this.docFormData = row;
				} else {
					this.docFormData =  {
						docName: '',
						filePath: '',
						fileSize: '',
						businessType: '3'
					};
				}
			},
			saveDoc() { //保存文档
				this.$http({
					url: '/api/file/info',
					method: 'POST',
					data: this.docFormData
				}).then( res => {
					// console.log(res.data);
					this.dialogVisible = false;
					this.docFiles = []
					this.$message.success('添加文档成功')
					this.loadTableData()
				})
			},
			editDoc() { //编辑文档
				this.$http({
					url: '/api/file/info/update',
					method: 'POST',
					data: this.docFormData
				}).then( res => {
					// console.log(res.data);
					this.dialogVisible = false;
					this.docFiles = []
					this.$message.success('修改文档成功')
					this.loadTableData()
				})
			},
			downloadDoc(row) { //下载文档
				this.$util.download(`/api/file/info/download/${row.fileId}`)
			},
			beforeUpload(file) { //上传文件钩子
				console.log(file);
				//记录文件大小
				this.docFormData.fileSize = file.size
			},
			uploadsuccess(response, file, fileList) { //文件上传成功钩子函数
				// console.log(response, file, fileList)
				this.docFormData.filePath = response.path
			},
			reset() { //重置查询表单
				this.searchFormData.docName = ''
				this.searchFormData.createdBy = ''
				this.searchFormData.beginDate = ''
				this.searchFormData.finishDate = ''
				this.searchFormData.dateRange = ''
				this.searchFormData.pageNum = 1
				this.dateRange= ['','']
				this.loadTableData()
			},
			search() { //搜索
				this.loadTableData()
			},
			pageSizeChange(pageSize) {
				this.searchFormData.pageNum = 1
				this.searchFormData.pageSize = pageSize
				this.loadTableData()
			},
			currentPageChange(pageNum) {
				this.searchFormData.pagenum = pageNum
				this.loadTableData()
			},
			loadTableData() { // 获取表格数据
				this.tableLoading = true;
				this.$http({
					url: '/api/file/info/list',
					method: 'POST',
					data: this.searchFormData
				}).then( res => {
					this.tableLoading = false;
					this.tableData = res.data.rows;
					this.searchFormData.total = res.data.total;
				})
			},
			async deleteDoc(row) { //删除文档
				const confirmResults = await this.$confirm('此操作将删除该文档，是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
				if (confirmResults === 'confirm') {
					let fIds = row.fileId || this.docSelection.map(f=>f.fileId).join(",");
					this.$http({
						url: `/api/file/info/delete/${fIds}`
					}).then( res => {
						this.$message.success('删除成功')
						this.loadTableData()
					})
				} else {
					this.$message.info('删除取消')
				}
			}
		}
		
	}
</script>
<style lang="scss" scoped>
	.docmanagement {
		height: calc(100vh - 100px);
		background-color: #f8f8f8;
		padding: 5px 30px 10px;

		.main {
			height: 92%;
			background-color: white;
			overflow-y: auto;
			padding: 30px;
			box-sizing: border-box;
			position: relative;

		}
	}
</style>
